package dao

import (
	"booksPro/model"
	"booksPro/utils"
	"net/http"
)

// 向数据库中 添加Session
func AddSession(session *model.Session) error {
	sqlStr := "insert into sessions values(?,?,?)"
	_, err := utils.Db.Exec(sqlStr, session.SessionID, session.Username, session.UserID)
	if err != nil {
		return err
	}
	return nil
}

func DeleteSession(sessionID string) error {
	sqlStr := "delete from sessions where session_id = ?"
	_, err := utils.Db.Exec(sqlStr, sessionID)
	if err != nil {
		return err
	}
	return nil
}

func GetSessionById(sessionID string) (*model.Session, error) {
	sqlStr := "select session_id,username,user_id from sessions where session_id = ?"
	//预编译
	inStmt, err := utils.Db.Prepare(sqlStr)
	if err != nil {
		return nil, err
	}
	row := inStmt.QueryRow(sessionID)
	session := &model.Session{}
	row.Scan(&session.SessionID, &session.Username, &session.UserID)
	return session, nil
}

func IsLogin(r *http.Request) (*model.Session, bool) {
	// 获取cookie 判断是否已经登录
	cookie, _ := r.Cookie("userId")
	if cookie != nil {
		//获取cookie的 value值
		cookieValue := cookie.Value
		//用 cookie的value 也就是sessionId 查询sessions表 是否该id的数据
		session, _ := GetSessionById(cookieValue)
		if session.UserID > 0 {
			return session, true
		}
	}
	return nil, false

}
